home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / site.py < prev    next >
Text File  |  2009-11-02  |  19KB  |  566 lines

  1. """Append module search paths for third-party packages to sys.path.
  2.  
  3. ****************************************************************
  4. * This module is automatically imported during initialization. *
  5. ****************************************************************
  6.  
  7. In earlier versions of Python (up to 1.5a3), scripts or modules that
  8. needed to use site-specific modules would place ``import site''
  9. somewhere near the top of their code.  Because of the automatic
  10. import, this is no longer necessary (but code that does it still
  11. works).
  12.  
  13. This will append site-specific paths to the module search path.  On
  14. Unix (including Mac OSX), it starts with sys.prefix and
  15. sys.exec_prefix (if different) and appends
  16. lib/python<version>/site-packages as well as lib/site-python.
  17. On other platforms (such as Windows), it tries each of the
  18. prefixes directly, as well as with lib/site-packages appended.  The
  19. resulting directories, if they exist, are appended to sys.path, and
  20. also inspected for path configuration files.
  21.  
  22. For Debian and derivatives, this sys.path is augmented with directories
  23. for packages distributed within the distribution. Local addons go
  24. into /usr/local/lib/python<version>/dist-packages, Debian addons
  25. install into /usr/{lib,share}/python<version>/dist-packages.
  26. /usr/lib/python<version>/site-packages is not used.
  27.  
  28. A path configuration file is a file whose name has the form
  29. <package>.pth; its contents are additional directories (one per line)
  30. to be added to sys.path.  Non-existing directories (or
  31. non-directories) are never added to sys.path; no directory is added to
  32. sys.path more than once.  Blank lines and lines beginning with
  33. '#' are skipped. Lines starting with 'import' are executed.
  34.  
  35. For example, suppose sys.prefix and sys.exec_prefix are set to
  36. /usr/local and there is a directory /usr/local/lib/python2.5/site-packages
  37. with three subdirectories, foo, bar and spam, and two path
  38. configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
  39. following:
  40.  
  41.   # foo package configuration
  42.   foo
  43.   bar
  44.   bletch
  45.  
  46. and bar.pth contains:
  47.  
  48.   # bar package configuration
  49.   bar
  50.  
  51. Then the following directories are added to sys.path, in this order:
  52.  
  53.   /usr/local/lib/python2.5/site-packages/bar
  54.   /usr/local/lib/python2.5/site-packages/foo
  55.  
  56. Note that bletch is omitted because it doesn't exist; bar precedes foo
  57. because bar.pth comes alphabetically before foo.pth; and spam is
  58. omitted because it is not mentioned in either path configuration file.
  59.  
  60. After these path manipulations, an attempt is made to import a module
  61. named sitecustomize, which can perform arbitrary additional
  62. site-specific customizations.  If this import fails with an
  63. ImportError exception, it is silently ignored.
  64.  
  65. """
  66.  
  67. import sys
  68. import os
  69. import __builtin__
  70.  
  71. # Prefixes for site-packages; add additional prefixes like /usr/local here
  72. PREFIXES = [sys.prefix, sys.exec_prefix]
  73. # Enable per user site-packages directory
  74. # set it to False to disable the feature or True to force the feature
  75. ENABLE_USER_SITE = None
  76. # for distutils.commands.install
  77. USER_SITE = None
  78. USER_BASE = None
  79.  
  80.  
  81. def makepath(*paths):
  82.     dir = os.path.abspath(os.path.join(*paths))
  83.     return dir, os.path.normcase(dir)
  84.  
  85.  
  86. def abs__file__():
  87.     """Set all module' __file__ attribute to an absolute path"""
  88.     for m in sys.modules.values():
  89.         if hasattr(m, '__loader__'):
  90.             continue   # don't mess with a PEP 302-supplied __file__
  91.         try:
  92.             m.__file__ = os.path.abspath(m.__file__)
  93.         except AttributeError:
  94.             continue
  95.  
  96.  
  97. def removeduppaths():
  98.     """ Remove duplicate entries from sys.path along with making them
  99.     absolute"""
  100.     # This ensures that the initial path provided by the interpreter contains
  101.     # only absolute pathnames, even if we're running from the build directory.
  102.     L = []
  103.     known_paths = set()
  104.     for dir in sys.path:
  105.         # Filter out duplicate paths (on case-insensitive file systems also
  106.         # if they only differ in case); turn relative paths into absolute
  107.         # paths.
  108.         dir, dircase = makepath(dir)
  109.         if not dircase in known_paths:
  110.             L.append(dir)
  111.             known_paths.add(dircase)
  112.     sys.path[:] = L
  113.     return known_paths
  114.  
  115. def _init_pathinfo():
  116.     """Return a set containing all existing directory entries from sys.path"""
  117.     d = set()
  118.     for dir in sys.path:
  119.         try:
  120.             if os.path.isdir(dir):
  121.                 dir, dircase = makepath(dir)
  122.                 d.add(dircase)
  123.         except TypeError:
  124.             continue
  125.     return d
  126.  
  127.  
  128. def addpackage(sitedir, name, known_paths):
  129.     """Process a .pth file within the site-packages directory:
  130.        For each line in the file, either combine it with sitedir to a path
  131.        and add that to known_paths, or execute it if it starts with 'import '.
  132.     """
  133.     if known_paths is None:
  134.         _init_pathinfo()
  135.         reset = 1
  136.     else:
  137.         reset = 0
  138.     fullname = os.path.join(sitedir, name)
  139.     try:
  140.         f = open(fullname, "rU")
  141.     except IOError:
  142.         return
  143.     with f:
  144.         for line in f:
  145.             if line.startswith("#"):
  146.                 continue
  147.             if line.startswith(("import ", "import\t")):
  148.                 exec line
  149.                 continue
  150.             line = line.rstrip()
  151.             dir, dircase = makepath(sitedir, line)
  152.             if not dircase in known_paths and os.path.exists(dir):
  153.                 sys.path.append(dir)
  154.                 known_paths.add(dircase)
  155.     if reset:
  156.         known_paths = None
  157.     return known_paths
  158.  
  159.  
  160. def addsitedir(sitedir, known_paths=None):
  161.     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  162.     'sitedir'"""
  163.     if known_paths is None:
  164.         known_paths = _init_pathinfo()
  165.         reset = 1
  166.     else:
  167.         reset = 0
  168.     sitedir, sitedircase = makepath(sitedir)
  169.     if not sitedircase in known_paths:
  170.         sys.path.append(sitedir)        # Add path component
  171.     try:
  172.         names = os.listdir(sitedir)
  173.     except os.error:
  174.         return
  175.     dotpth = os.extsep + "pth"
  176.     names = [name for name in names if name.endswith(dotpth)]
  177.     for name in sorted(names):
  178.         addpackage(sitedir, name, known_paths)
  179.     if reset:
  180.         known_paths = None
  181.     return known_paths
  182.  
  183.  
  184. def check_enableusersite():
  185.     """Check if user site directory is safe for inclusion
  186.  
  187.     The function tests for the command line flag (including environment var),
  188.     process uid/gid equal to effective uid/gid.
  189.  
  190.     None: Disabled for security reasons
  191.     False: Disabled by user (command line option)
  192.     True: Safe and enabled
  193.     """
  194.     if sys.flags.no_user_site:
  195.         return False
  196.  
  197.     if hasattr(os, "getuid") and hasattr(os, "geteuid"):
  198.         # check process uid == effective uid
  199.         if os.geteuid() != os.getuid():
  200.             return None
  201.     if hasattr(os, "getgid") and hasattr(os, "getegid"):
  202.         # check process gid == effective gid
  203.         if os.getegid() != os.getgid():
  204.             return None
  205.  
  206.     return True
  207.  
  208.  
  209. def addusersitepackages(known_paths):
  210.     """Add a per user site-package to sys.path
  211.  
  212.     Each user has its own python directory with site-packages in the
  213.     home directory.
  214.  
  215.     USER_BASE is the root directory for all Python versions
  216.  
  217.     USER_SITE is the user specific site-packages directory
  218.  
  219.     USER_SITE/.. can be used for data.
  220.     """
  221.     global USER_BASE, USER_SITE, ENABLE_USER_SITE
  222.     env_base = os.environ.get("PYTHONUSERBASE", None)
  223.  
  224.     def joinuser(*args):
  225.         return os.path.expanduser(os.path.join(*args))
  226.  
  227.     #if sys.platform in ('os2emx', 'riscos'):
  228.     #    # Don't know what to put here
  229.     #    USER_BASE = ''
  230.     #    USER_SITE = ''
  231.     if os.name == "nt":
  232.         base = os.environ.get("APPDATA") or "~"
  233.         USER_BASE = env_base if env_base else joinuser(base, "Python")
  234.         USER_SITE = os.path.join(USER_BASE,
  235.                                  "Python" + sys.version[0] + sys.version[2],
  236.                                  "site-packages")
  237.     else:
  238.         USER_BASE = env_base if env_base else joinuser("~", ".local")
  239.         USER_SITE = os.path.join(USER_BASE, "lib",
  240.                                  "python" + sys.version[:3],
  241.                                  "site-packages")
  242.  
  243.     if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
  244.         addsitedir(USER_SITE, known_paths)
  245.     if ENABLE_USER_SITE:
  246.         for dist_libdir in ("lib", "local/lib"):
  247.             user_site = os.path.join(USER_BASE, dist_libdir,
  248.                                      "python" + sys.version[:3],
  249.                                      "dist-packages")
  250.             if os.path.isdir(user_site):
  251.                 addsitedir(user_site, known_paths)
  252.     return known_paths
  253.  
  254.  
  255. def addsitepackages(known_paths):
  256.     """Add site-packages (and possibly site-python) to sys.path"""
  257.     sitedirs = []
  258.     seen = []
  259.  
  260.     for prefix in PREFIXES:
  261.         if not prefix or prefix in seen:
  262.             continue
  263.         seen.append(prefix)
  264.  
  265.         if sys.platform in ('os2emx', 'riscos'):
  266.             sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
  267.         elif os.sep == '/':
  268.             sitedirs.append(os.path.join(prefix, "lib",
  269.                                         "python" + sys.version[:3],
  270.                                         "dist-packages"))
  271.             sitedirs.append(os.path.join(prefix, "local/lib",
  272.                                         "python" + sys.version[:3],
  273.                                         "dist-packages"))
  274.             sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
  275.         else:
  276.             sitedirs.append(prefix)
  277.             sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
  278.  
  279.         if sys.platform == "darwin":
  280.             # for framework builds *only* we add the standard Apple
  281.             # locations. Currently only per-user, but /Library and
  282.             # /Network/Library could be added too
  283.             if 'Python.framework' in prefix:
  284.                 sitedirs.append(
  285.                     os.path.expanduser(
  286.                         os.path.join("~", "Library", "Python",
  287.                                      sys.version[:3], "site-packages")))
  288.  
  289.     for sitedir in sitedirs:
  290.         if os.path.isdir(sitedir):
  291.             addsitedir(sitedir, known_paths)
  292.  
  293.     return known_paths
  294.  
  295.  
  296. def setBEGINLIBPATH():
  297.     """The OS/2 EMX port has optional extension modules that do double duty
  298.     as DLLs (and must use the .DLL file extension) for other extensions.
  299.     The library search path needs to be amended so these will be found
  300.     during module import.  Use BEGINLIBPATH so that these are at the start
  301.     of the library search path.
  302.  
  303.     """
  304.     dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  305.     libpath = os.environ['BEGINLIBPATH'].split(';')
  306.     if libpath[-1]:
  307.         libpath.append(dllpath)
  308.     else:
  309.         libpath[-1] = dllpath
  310.     os.environ['BEGINLIBPATH'] = ';'.join(libpath)
  311.  
  312.  
  313. def setquit():
  314.     """Define new built-ins 'quit' and 'exit'.
  315.     These are simply strings that display a hint on how to exit.
  316.  
  317.     """
  318.     if os.sep == ':':
  319.         eof = 'Cmd-Q'
  320.     elif os.sep == '\\':
  321.         eof = 'Ctrl-Z plus Return'
  322.     else:
  323.         eof = 'Ctrl-D (i.e. EOF)'
  324.  
  325.     class Quitter(object):
  326.         def __init__(self, name):
  327.             self.name = name
  328.         def __repr__(self):
  329.             return 'Use %s() or %s to exit' % (self.name, eof)
  330.         def __call__(self, code=None):
  331.             # Shells like IDLE catch the SystemExit, but listen when their
  332.             # stdin wrapper is closed.
  333.             try:
  334.                 sys.stdin.close()
  335.             except:
  336.                 pass
  337.             raise SystemExit(code)
  338.     __builtin__.quit = Quitter('quit')
  339.     __builtin__.exit = Quitter('exit')
  340.  
  341.  
  342. class _Printer(object):
  343.     """interactive prompt objects for printing the license text, a list of
  344.     contributors and the copyright notice."""
  345.  
  346.     MAXLINES = 23
  347.  
  348.     def __init__(self, name, data, files=(), dirs=()):
  349.         self.__name = name
  350.         self.__data = data
  351.         self.__files = files
  352.         self.__dirs = dirs
  353.         self.__lines = None
  354.  
  355.     def __setup(self):
  356.         if self.__lines:
  357.             return
  358.         data = None
  359.         for dir in self.__dirs:
  360.             for filename in self.__files:
  361.                 filename = os.path.join(dir, filename)
  362.                 try:
  363.                     fp = file(filename, "rU")
  364.                     data = fp.read()
  365.                     fp.close()
  366.                     break
  367.                 except IOError:
  368.                     pass
  369.             if data:
  370.                 break
  371.         if not data:
  372.             data = self.__data
  373.         self.__lines = data.split('\n')
  374.         self.__linecnt = len(self.__lines)
  375.  
  376.     def __repr__(self):
  377.         self.__setup()
  378.         if len(self.__lines) <= self.MAXLINES:
  379.             return "\n".join(self.__lines)
  380.         else:
  381.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  382.  
  383.     def __call__(self):
  384.         self.__setup()
  385.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  386.         lineno = 0
  387.         while 1:
  388.             try:
  389.                 for i in range(lineno, lineno + self.MAXLINES):
  390.                     print self.__lines[i]
  391.             except IndexError:
  392.                 break
  393.             else:
  394.                 lineno += self.MAXLINES
  395.                 key = None
  396.                 while key is None:
  397.                     key = raw_input(prompt)
  398.                     if key not in ('', 'q'):
  399.                         key = None
  400.                 if key == 'q':
  401.                     break
  402.  
  403. def setcopyright():
  404.     """Set 'copyright' and 'credits' in __builtin__"""
  405.     __builtin__.copyright = _Printer("copyright", sys.copyright)
  406.     if sys.platform[:4] == 'java':
  407.         __builtin__.credits = _Printer(
  408.             "credits",
  409.             "Jython is maintained by the Jython developers (www.jython.org).")
  410.     else:
  411.         __builtin__.credits = _Printer("credits", """\
  412.     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  413.     for supporting Python development.  See www.python.org for more information.""")
  414.     here = os.path.dirname(os.__file__)
  415.     __builtin__.license = _Printer(
  416.         "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  417.         ["LICENSE.txt", "LICENSE"],
  418.         [os.path.join(here, os.pardir), here, os.curdir])
  419.  
  420.  
  421. class _Helper(object):
  422.     """Define the built-in 'help'.
  423.     This is a wrapper around pydoc.help (with a twist).
  424.  
  425.     """
  426.  
  427.     def __repr__(self):
  428.         return "Type help() for interactive help, " \
  429.                "or help(object) for help about object."
  430.     def __call__(self, *args, **kwds):
  431.         import pydoc
  432.         return pydoc.help(*args, **kwds)
  433.  
  434. def sethelper():
  435.     __builtin__.help = _Helper()
  436.  
  437. def aliasmbcs():
  438.     """On Windows, some default encodings are not provided by Python,
  439.     while they are always available as "mbcs" in each locale. Make
  440.     them usable by aliasing to "mbcs" in such a case."""
  441.     if sys.platform == 'win32':
  442.         import locale, codecs
  443.         enc = locale.getdefaultlocale()[1]
  444.         if enc.startswith('cp'):            # "cp***" ?
  445.             try:
  446.                 codecs.lookup(enc)
  447.             except LookupError:
  448.                 import encodings
  449.                 encodings._cache[enc] = encodings._unknown
  450.                 encodings.aliases.aliases[enc] = 'mbcs'
  451.  
  452. def setencoding():
  453.     """Set the string encoding used by the Unicode implementation.  The
  454.     default is 'ascii', but if you're willing to experiment, you can
  455.     change this."""
  456.     encoding = "ascii" # Default value set by _PyUnicode_Init()
  457.     if 0:
  458.         # Enable to support locale aware default string encodings.
  459.         import locale
  460.         loc = locale.getdefaultlocale()
  461.         if loc[1]:
  462.             encoding = loc[1]
  463.     if 0:
  464.         # Enable to switch off string to Unicode coercion and implicit
  465.         # Unicode to string conversion.
  466.         encoding = "undefined"
  467.     if encoding != "ascii":
  468.         # On Non-Unicode builds this will raise an AttributeError...
  469.         sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  470.  
  471.  
  472. def execsitecustomize():
  473.     """Run custom site specific code, if available."""
  474.     try:
  475.         import sitecustomize
  476.     except ImportError:
  477.         pass
  478.  
  479.  
  480. def execusercustomize():
  481.     """Run custom user specific code, if available."""
  482.     try:
  483.         import usercustomize
  484.     except ImportError:
  485.         pass
  486.  
  487.  
  488. def main():
  489.     global ENABLE_USER_SITE
  490.  
  491.     abs__file__()
  492.     known_paths = removeduppaths()
  493.     if ENABLE_USER_SITE is None:
  494.         ENABLE_USER_SITE = check_enableusersite()
  495.     known_paths = addusersitepackages(known_paths)
  496.     known_paths = addsitepackages(known_paths)
  497.     if sys.platform == 'os2emx':
  498.         setBEGINLIBPATH()
  499.     setquit()
  500.     setcopyright()
  501.     sethelper()
  502.     aliasmbcs()
  503.     setencoding()
  504.     execsitecustomize()
  505.     if ENABLE_USER_SITE:
  506.         execusercustomize()
  507.     # Remove sys.setdefaultencoding() so that users cannot change the
  508.     # encoding after initialization.  The test for presence is needed when
  509.     # this module is run as a script, because this code is executed twice.
  510.     if hasattr(sys, "setdefaultencoding"):
  511.         del sys.setdefaultencoding
  512.  
  513. main()
  514.  
  515. def _script():
  516.     help = """\
  517.     %s [--user-base] [--user-site]
  518.  
  519.     Without arguments print some useful information
  520.     With arguments print the value of USER_BASE and/or USER_SITE separated
  521.     by '%s'.
  522.  
  523.     Exit codes with --user-base or --user-site:
  524.       0 - user site directory is enabled
  525.       1 - user site directory is disabled by user
  526.       2 - uses site directory is disabled by super user
  527.           or for security reasons
  528.      >2 - unknown error
  529.     """
  530.     args = sys.argv[1:]
  531.     if not args:
  532.         print "sys.path = ["
  533.         for dir in sys.path:
  534.             print "    %r," % (dir,)
  535.         print "]"
  536.         print "USER_BASE: %r (%s)" % (USER_BASE,
  537.             "exists" if os.path.isdir(USER_BASE) else "doesn't exist")
  538.         print "USER_SITE: %r (%s)" % (USER_SITE,
  539.             "exists" if os.path.isdir(USER_SITE) else "doesn't exist")
  540.         print "ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE
  541.         sys.exit(0)
  542.  
  543.     buffer = []
  544.     if '--user-base' in args:
  545.         buffer.append(USER_BASE)
  546.     if '--user-site' in args:
  547.         buffer.append(USER_SITE)
  548.  
  549.     if buffer:
  550.         print os.pathsep.join(buffer)
  551.         if ENABLE_USER_SITE:
  552.             sys.exit(0)
  553.         elif ENABLE_USER_SITE is False:
  554.             sys.exit(1)
  555.         elif ENABLE_USER_SITE is None:
  556.             sys.exit(2)
  557.         else:
  558.             sys.exit(3)
  559.     else:
  560.         import textwrap
  561.         print textwrap.dedent(help % (sys.argv[0], os.pathsep))
  562.         sys.exit(10)
  563.  
  564. if __name__ == '__main__':
  565.     _script()
  566.